package com.bigevent.bigevent.intercepter;

import com.bigevent.bigevent.common.CommonVal;
import com.bigevent.bigevent.utils.JwtUtil;
import com.bigevent.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;

/**
 * @author yangxudong
 * @description: 登录拦截
 * @date 2024/2/3 21:46
 */
@Component
public class LoginIntercepter implements HandlerInterceptor {
    private static Logger LOGGER = LoggerFactory.getLogger(LoginIntercepter.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwtToken = request.getHeader("Authorization");
        if (StringUtils.hasLength(jwtToken)) {
            String redisToken = redisTemplate.opsForValue().get(CommonVal.REDIS_TOKEN_KEY + jwtToken);
            if (!ObjectUtils.nullSafeEquals(jwtToken, redisToken)) {
                LOGGER.warn("token is invalid");
                dealResponse(response);
                return false;
            }
            Map<String, Object> userInfo = null;
            try {
                userInfo = JwtUtil.parseToken(jwtToken);
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.warn("token解析失败");
                dealResponse(response);
                return false;
            }
            ThreadLocalUtil.set(userInfo);
            return true;
        }
        dealResponse(response);
        // 记录日志
        LOGGER.warn("用户未登录");
        // 返回false，不再继续执行
        return false;
    }

    private static void dealResponse(HttpServletResponse response) throws IOException {
        response.setStatus(401);
        response.getWriter().write("user not login");
        response.getWriter().flush();
        response.getWriter().close();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
